package top.huxy.boot.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import top.huxy.boot.config.RedisKeyConfig;
import top.huxy.boot.exception.RequestAbortedException;
import top.huxy.boot.mapper.AdminMapper;
import top.huxy.boot.model.entity.Admin;
import top.huxy.boot.model.vo.VOAdmin;
import top.huxy.boot.service.AdminService;
import top.huxy.boot.util.IPAddressUtils;
import top.huxy.boot.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Override
    public int addAdmin(Admin admin) {
        //密码加密
        admin.setPassword(StringUtils.encryption(admin.getPassword()));
        return adminMapper.addAdmin(admin);
    }

    @Override
    public VOAdmin doLogin(String username, String password, String yzm, String admin_token) {
        //请求的ip地址
        String requestIp = IPAddressUtils.getRequestIp();

        //验证码正确性判断
        Object o = redisTemplate.opsForValue().get(RedisKeyConfig.YZM_PREFIX + requestIp);
        if (StringUtils.isEmpty(o)||!o.toString().equalsIgnoreCase(yzm)) throw new RequestAbortedException("验证码错误");

        //验证码只能用一次，验证成功了就清除
        redisTemplate.delete(RedisKeyConfig.YZM_PREFIX + requestIp);

        //用户名与密码校验
        Admin admin = adminMapper.getAdmin(username,StringUtils.encryption(password));
        if (admin == null) {
            throw new RequestAbortedException("用户名或密码错误");
        }

        //如果携带了token，就从redis中删除旧的该记录
        if (!StringUtils.isEmpty(admin_token)) {
            redisTemplate.delete(admin_token);
        }

        //生成token
        admin_token=StringUtils.unique();

        //生成VO

        VOAdmin voAdmin=new VOAdmin(admin);
        voAdmin.setToken(admin_token);

        //缓存
        redisTemplate.opsForValue().set(admin_token,admin,1L,TimeUnit.DAYS);

        return voAdmin;
    }
}
